const cheerio = require('cheerio');
const curl = require('./curl');
const xlsx = require('./xlsx');

const get_world_data = function () {
  const url = "https://interface.sina.cn/news/wap/fymap2020_data.d.json";

  return new Promise(function (resolve, reject) {
    curl.download(url, function (res) {
      if (res) {
        let res_json = JSON.parse(res);
        console.log('获取新浪数据成功！');
        resolve(res_json);
      } else {
        reject('获取新浪数据失败！')
      }
    })
  });
}

const get_data = async function (file) {
  let n_data = await get_world_data();
  let data = n_data.data;

  let lastUpdateTime = data.mtime;
  let add_daily = data.add_daily;
  let historylist = data.historylist;
  let china_list = data.list;
  let worldlist = data.worldlist;

  let headers = ['确诊总数', '死亡总数', '治愈总数', '疑似总数'];

  let world_array = [
    ['国家', ...headers, '更新时间']
  ];

  let china_province_array = [
    ['省份', ...headers, '更新时间']
  ];

  let china_district_array = [['省份', '地区', ...headers, '更新时间']];

  let history_array = [
    ['时间', ...headers, ...headers.map(ele => '武汉' + ele)]
  ];

  worldlist.forEach(ele => {
    world_array.push([
      ele.name, ele.value, ele.deathNum, ele.cureNum, ele.susNum, lastUpdateTime
    ])
  });

  historylist.forEach(ele => {
    history_array.push([
      ele.date, ele.cn_conNum, ele.cn_deathNum, ele.cn_cureNum, ele.cn_susNum,
      ele.wuhan_conNum, ele.wuhan_deathNum, ele.wuhan_cureNum, ele.wjw_susNum
    ]);
  });

  china_list.forEach(p => {
    china_province_array.push([
      p.name, p.value, p.deathNum, p.cureNum, p.susNum, lastUpdateTime
    ]);

    p.city.forEach(ele => {
      china_district_array.push([
        p.name, ele.name, ele.conNum, ele.deathNum, ele.cureNum, ele.susNum, lastUpdateTime
      ]);
    })
  });

  let chinaTotal_array = [
    ['确诊', data.gntotal],
    ['死亡', data.deathtotal],
    ['治愈', data.curetotal],
    ['疑似', data.sustotal],
    ['确诊变化', add_daily.addcon],
    ['死亡变化', add_daily.adddeath],
    ['治愈变化', add_daily.addcure],
    ['疑似变化', add_daily.addsus],
    ['时间', lastUpdateTime]
  ]

  let new_file = new xlsx.Xlsx(file);

  new_file.add({
    name: '国际情况',
    data: world_array
  });

  new_file.add({
    name: '国内情况',
    data: chinaTotal_array
  });

  new_file.add({
    name: '各省情况',
    data: china_province_array
  });

  new_file.add({
    name: '地市情况',
    data: china_district_array
  });

  new_file.add({
    name: '国内每日',
    data: history_array
  });

  await new_file.writeFileSync();
}

exports.get_data = get_data;